package com.xander.myblog.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.xander.myblog.VO.OwnerVO;
import com.xander.myblog.constant.Constants;
import com.xander.myblog.entity.Article;
import com.xander.myblog.entity.Topic;
import com.xander.myblog.entity.User;
import com.xander.myblog.service.ArticleService;
import com.xander.myblog.service.TopicService;
import com.xander.myblog.service.UserService;
import com.xander.myblog.util.ArticleUtil;
import com.xander.myblog.util.ShortUUIDUtil;
import com.xander.myblog.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 叶振东
 * @date 2018-11-16
 */
@Controller
public class HomeController {
    @Autowired
    private TopicService topicService;
    @Autowired
    private ArticleService articleService;

    String articlesString = "articles";

    @GetMapping("/")
    public String toIndex() {
        return "forward:index";
    }

    @GetMapping("index")
    public String index(HttpSession session,HttpServletRequest request) {
        if (null == session.getAttribute(articlesString)) {
            PageInfo<Article> articles = articleService.getArticleListByDate(1, 5);
            articles = ArticleUtil.cutArticles(articles);
            request.setAttribute(articlesString, articles);
        }
        return "index";
    }

    @GetMapping("topic/{tid}/page/{page}")
    public String topic(@PathVariable("tid") Long tid, @PathVariable("page") Integer page, HttpServletRequest request) {
        if (tid != null) {
            Topic topic = topicService.getTopicByTid(tid);
            PageInfo articles = articleService.getArticleListByTid(tid, page == null ? 1 : page, 5);
            articles = ArticleUtil.cutArticles(articles);
            request.setAttribute("topic", topic);
            request.setAttribute("articles", articles);
            return "topic";
        } else {
            return "error";
        }
    }

    @GetMapping("page/{page}")
    public String topic(@PathVariable("page") Integer page, HttpServletRequest request) {
        PageInfo<Article> pageInfo = articleService.getArticleListByDate(page == null ? 1 : page == null ? 1 : page, 5);
        pageInfo = ArticleUtil.cutArticles(pageInfo);
        request.setAttribute("articles", pageInfo);
        return "index";

    }

    @PostMapping("upload")
    @ResponseBody
    public String uploadAvatar(@RequestParam("file") MultipartFile files[], HttpServletRequest request) {
        String uploadPath = request.getServletContext().getRealPath("/WEB-INF/classes/static/static/img/upload");
        String contextPath = request.getServletContext().getContextPath();
        JSONObject result = new JSONObject();
        List imgList = new ArrayList<String>();
        File uploadDirectory = new File(uploadPath);
        if (uploadDirectory.exists()) {
            if (!uploadDirectory.isDirectory()) {
                uploadDirectory.delete();
            }
        } else {
            uploadDirectory.mkdir();
        }
        //这里可以支持多文件上传
        if (files != null && files.length >= 1) {
            try {
                for (MultipartFile file : files) {
                    String originalFilename = file.getOriginalFilename();
                    //判断是否有文件且是否为图片文件
                    if (originalFilename != null && !"".equalsIgnoreCase(originalFilename.trim())) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
                        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
                        String fileName = sdf.format(new Date()) + "_" + ShortUUIDUtil.getShortUUID() + "." + suffix;
                        System.out.println(fileName);
                        file.transferTo(new File(uploadPath + File.separator + fileName));
                        imgList.add(contextPath + "/static/img/upload/" + fileName);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                result.put("errno", 1);
            }
            result.put("errno", 0);
        }
        result.put("data", imgList);
        return result.toString();
    }

    @GetMapping("captcha")
    @ResponseBody
    public void captcha(HttpSession session, HttpServletResponse response) throws Exception {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        String code = VerifyCodeUtils.generateVerifyCode(4);
        session.removeAttribute("captcha");
        session.setAttribute("captcha", code);
        int w = 100, h = 30;
        VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), code);
    }
}
